<template>
  <div class="element-tree">
    <!-- 树组件 -->
    <h2>树组件</h2>
    <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
    <el-tree
      class="filter-tree"
      :data="treeData"
      :props="defaultProps"
      default-expand-all
      :filter-node-method="filterNode"
      ref="treeRef"
    ></el-tree>
  </div>
</template>

<script>
// eslint-disable-next-line
import { ref, reactive, watchEffect, watch, onMounted } from 'vue'
export default {
  name: 'ElementTree',
  setup() {
    const treeRef = ref()
    let filterText = ref()
    const treeData = reactive([
      {
        id: 1,
        label: '一级 1',
        children: [
          {
            id: 4,
            label: '二级 1-1',
            children: [
              {
                id: 9,
                label: '三级 1-1-1'
              },
              {
                id: 10,
                label: '三级 1-1-2'
              }
            ]
          }
        ]
      },
      {
        id: 2,
        label: '一级 2',
        children: [
          {
            id: 5,
            label: '二级 2-1'
          },
          {
            id: 6,
            label: '二级 2-2'
          }
        ]
      },
      {
        id: 3,
        label: '一级 3',
        children: [
          {
            id: 7,
            label: '二级 3-1'
          },
          {
            id: 8,
            label: '二级 3-2'
          }
        ]
      }
    ])
    const defaultProps = reactive({
      children: 'children',
      label: 'label'
    })
    const filterNode = (value, data) => {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
    /**
     * watch和watchEffect皆可filter,
     * treeRef.value.filter - 需要在页面加载完毕后执行
     */
    onMounted(() => {
      watchEffect(() => {
        treeRef.value.filter(filterText.value)
      })
    })
    // watch([filterText], ([newFilter]) => {
    //   treeRef.value.filter(newFilter)
    // })
    return {
      treeRef,
      filterText,
      treeData,
      defaultProps,
      filterNode
    }
  }
}
</script>
<style lang="scss">
.element-tree {
  margin: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  text-align: left;
  h2 {
    margin: 10px 0;
  }
}
</style>
